package com.zzzzzz.account.signup;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.account.Constants;
import com.zzzzzz.account.EmailSend;
import com.zzzzzz.account.MailService;
import com.zzzzzz.account.ticket.Ticket;
import com.zzzzzz.account.ticket.TicketDao;
import com.zzzzzz.account.user.User;
import com.zzzzzz.account.user.UserAlreadyExistsException;
import com.zzzzzz.account.user.UserDao;
import com.zzzzzz.common.GlobalConstants;
import com.zzzzzz.common.util.StringPool;

@Service("signupService")
public class SignupServiceImpl implements SignupService {
	
	@Resource
	private UserDao userDao;
	@Resource
	private TicketDao ticketDao;
	@Resource
	private MailService mailService;

	/* 
	 * transactional (add User & add Ticket)
	 */
	@Transactional
	public void add(User user, HttpServletRequest request) throws UserAlreadyExistsException {
		userDao.add(user);
		sendAccountActivationEmail(user.getId(), request);
	}
	
	public void sendAccountActivationEmail(Long userId, HttpServletRequest request) {
		User user = userDao.findById(userId, GlobalConstants.STATUS.INACTIVE);
		Ticket ticket = ticketDao.add(user.getId(), Constants.TICKET_TYPE.ACCOUNT_ACTIVATION);
		
		String activationURL = request.getServerName() + StringPool.COLON + request.getServerPort() + request.getContextPath() + "/account/activate/" + ticket.getKey();
		System.out.println("Activation URL: " + activationURL);
		EmailSend emailSend = new EmailSend();
		emailSend.setSendTo(user.getEmail());
		emailSend.setSendFrom(EmailSend.DEFAULT_SENDTO);
		emailSend.setSubject(EmailSend.REGISTER_ACTIVATE_SUBJECT);
		emailSend.setHtmlTemplate(EmailSend.TEMPLATE.CONFIRM_ACCOUNT_TEMPLATE);
		Map<String,Object> htmlData = new HashMap<String,Object>();
		htmlData.put("username", user.getUsername());
		htmlData.put("activation_url", activationURL);
		emailSend.setHtmlData(htmlData);
		mailService.sendMail(emailSend);
	}
	
	public User activate(Long userId) {
		User user = userDao.findById(userId, GlobalConstants.STATUS.INACTIVE);
		if(user!=null){
			userDao.editStatus(userId, 0);
		}
		return user;
	}
	

}
